'''
Created on Sep 7, 2012

@author: DuongThanh
'''
import nltk
from tool.OutputResult import OutputResult
from svmutil import svm_train
from  svmutil import * 

from math import pow

trainFeatureMerge = "../../data/lemmaFeaturesTrain_300.csv"
testFeatureMerge  = "../../data/lemmaFeaturesTest_300.csv"
resultFile        =  "../../data/output_SVM_300.csv"

labels = []
features = []
featuresTest = []
def getLabelAndFeatures(fileName):    
    labeledFeatures = []
    # TRAIN THE MODEL 
    file1 = open(fileName)
    for line in file1:
        line = line.strip()
        all = line.split(",")
        feature = {}
        for i in range(0,(len(all)-1)):
            feature[i] = float(all[i])
        label = int(all[len(all)-1])
        # add label
        labels.append(label)
        # a tuple 
        features.append(feature)
        #print features
    file1.close()
        
def getFeaturesTestData(testFileName):
    # RUN ON TEST DATA
    file2 = open(testFileName)
    result = []
    for line in file2:
        line = line.strip()
        all = line.split(",")
        feature = {}
        for i in range(0,(len(all))):
            feature[i] = float(all[i])
        # a tuple 
        featuresTest.append(feature)
        #print features
    file2.close()
    
# MAIN PART ###
###############
# Get labeled features     
 
getLabelAndFeatures(trainFeatureMerge)  
m = svm_train(labels, features, '-b 1 -c 32 -g '+str(pow(2,-9)))
#print m
#exit(0)
#cost = [-11,-12,-13,-14,-15]

#for c in cost:
#    f = open("temp.t"+str(c),"w")
#    value = pow(2,c)
#    m = svm_train(labels, features, '-v 10 -c 32 -g '+str(value))
#    f.write("Test with gamma = " + str(c)+ "\n")
#    f.write(str(m)+"\n")
#    f.close()

#exit(0)

getFeaturesTestData(testFeatureMerge)

label_test = []
for i in range(0,len(featuresTest)):
    label_test.append(0)
#print m.label
 
p_label, p_acc, p_val = svm_predict(label_test, featuresTest, m," -b 1")

# Write to output 
import csv
fileOut=open(resultFile,'wb')
testFile = open("../../data/test.csv")
spamReader = csv.reader(testFile,delimiter = ",")
spamWriter = csv.writer(fileOut, delimiter = ",")
count = 0
output = OutputResult()

for line in spamReader:
    count+=1 
    if (count ==1):
        line = line + ["Prediction"]
    else:
        t1 = (count-2) / 6 
        label = line[0]
        key = 5
        if (label == "population"): key = 1
        if (label == "intervention"): key = 3 
        if (label == "background"): key = 2
        if (label == "outcome"): key = 4
        if (label == "study design"): key = 5
        if (label == "other"): key = 0
        prob = p_val[t1][key]       
        line  = line + [str(output.f(prob,5))]  
    spamWriter.writerow(line)

testFile.close()    
fileOut.close()
